//
//  CheckHeartBeat.m
//  TcpTest_Server
//
//  Created by scarlettsun on 12-7-28.
//  Copyright (c) 2012年 tencent. All rights reserved.
//

#import "CheckHeartBeat.h"
#import "MainSocketDelegate.h"
#import "LogOutPacketCenter.h"
#import "SockPacket.h"
#import "MiniSocket.h"

@implementation CheckHeartBeat

- (id)init
{
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"defaults" ofType:@"plist"];  
    NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
    
    NSNumber *heartBeatTimeIntervalNum = [data objectForKey:@"HeartBeatTimeInterval"];
    heartBeatTimeInterval = [heartBeatTimeIntervalNum intValue];
    
    NSNumber *fallLineTimeIntervalNum = [data objectForKey:@"FallLineTimeInterval"];
    fallLineTimeInterval = [fallLineTimeIntervalNum intValue];
    
    logOutPacketDelegate = [[LogOutPacketCenter alloc] init];
    
    [[NSNotificationCenter defaultCenter] addObserver:logOutPacketDelegate selector:@selector(sendFallLinePacket:) name:SendFallLinePacket object:nil];
    
    return [super init];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:logOutPacketDelegate];
}

-(void) doOnlineCheck
{
    /*
     
     check the heart beat queue;
     
     */
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSLog(@"do heart beat check");
        while (true) {
            
            NSMutableArray *deleteUserIdArray = [[NSMutableArray alloc] init];  // theHeartBeatQueue 中已经被判断为掉线的QQ号
            
            @synchronized([MainSocketDelegate theHeartBeatQueue])
            {
                for (int i = 0; i< [[MainSocketDelegate theHeartBeatQueue] count]; ++i) 
                {
                    HeartBeat *_heartBeat = ( HeartBeat *)[[MainSocketDelegate theHeartBeatQueue] objectAtIndex:i];
                    NSTimeInterval interval = -1*[_heartBeat.beatTime timeIntervalSinceNow];
                    if (interval > fallLineTimeInterval)
                    {
                         
                        NSNumber *idNum = [NSNumber numberWithInt:(int)_heartBeat.userId];
                        NSDictionary *userInfo = [NSDictionary dictionaryWithObject:idNum forKey:@"idNum"];
                        [[NSNotificationCenter defaultCenter] postNotificationName:SendFallLinePacket object:nil userInfo:userInfo];
                        [[MainSocketDelegate theHeartBeatQueue] removeObject:_heartBeat];
                        [deleteUserIdArray addObject:[NSNumber numberWithInt:_heartBeat.userId]];
                    }
                }
            }
            
            @synchronized([MainSocketDelegate connectedSocketsQueue])  // 从 connectedSocketsQueue 中删除所有已经被udonr为掉线的 
            {
                for (NSNumber *deleteUserIdNum in deleteUserIdArray)
                {
                    NSInteger deleteUserId = [deleteUserIdNum intValue];
                    for (int i = 0; i < [[MainSocketDelegate connectedSocketsQueue] count]; i++) 
                    {
                        MiniSocket *sock  = [[MainSocketDelegate connectedSocketsQueue] objectAtIndex:i];
                        if (deleteUserId == sock.userId)
                        {
                            [sock.miniAsynSocket disconnect];
                            [[MainSocketDelegate connectedSocketsQueue] removeObject:sock];
                        }
                    }
                }
            }
             
            sleep(heartBeatTimeInterval*0.5);  
        }
        
    });
}

@end
